﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using OpenQuarters.WebQuarters.Utils;
using OpenQuarters.WebQuarters.Core;
using OpenQuarters.WebQuarters.Modules.Core;

namespace OpenQuarters.WebQuarters.Core.Web.Areas.Site.Views.Shared
{
    public class TemplateBaseBase<T> : System.Web.Mvc.ViewPage<T> where T : class
    {
        protected HtmlContainerControl firstContentArea = null;
        protected HtmlContainerControl defaultContentArea = null;
        protected List<KeyValuePair<ModuleDefinition, Control>> modulesToAdd = new List<KeyValuePair<ModuleDefinition, Control>>();
        private int totalModules = 0;
        private int totalNonInheritedModules = 0;

        protected override void OnInit(EventArgs e)
        {
            if (Oracle.GetSettings().GZipEnabled.HasValue)
            {
                if (Oracle.GetSettings().GZipEnabled.Value)
                    GeneralUtils.GZipIfSupported();
            }

            base.OnInit(e);

            CSS.RegisterStyleSheet("Core.cmsEditor.css", "OpenQuarters.WebQuarters.Core.Web", "Areas.CMS.Content.Css.cmsEditor.css", CSSType.AdminStyleSheet);

            SetupContentAreas(null);

            if (this.defaultContentArea == null && this.firstContentArea != null)
            {
                this.defaultContentArea = this.firstContentArea;
            }

            if (defaultContentArea != null && CMSPage.Current.ContentDefinition["ContentArea.Default"].Modules.Count > 0)
            {
                totalModules += CMSPage.Current.ContentDefinition["ContentArea.Default"].Modules.Count;
                CMSPage.Current.ContentDefinition["ContentArea.Default"].Modules.ForEach(m => modulesToAdd.Add(new KeyValuePair<ModuleDefinition, Control>(m, defaultContentArea)));
            }

            if (firstContentArea != null && CMSPage.Current.ContentDefinition["ContentArea.First"].Modules.Count > 0)
            {
                totalModules += CMSPage.Current.ContentDefinition["ContentArea.First"].Modules.Count;
                CMSPage.Current.ContentDefinition["ContentArea.First"].Modules.ForEach(m => modulesToAdd.Add(new KeyValuePair<ModuleDefinition, Control>(m, firstContentArea)));
            }

            if (totalModules == 0 && this.defaultContentArea != null)
            {
                modulesToAdd.Add(new KeyValuePair<ModuleDefinition,Control>(
                    new ContentModule().ToDefinition(),
                    defaultContentArea)
                );
            }

            foreach (var kv in modulesToAdd)
            {
                kv.Key.InstantiateIn(kv.Value);
            }
        }

        private void SetupContentAreas(ControlCollection controls)
        {
            if (controls == null)
            {
                controls = this.Controls;
            }

            for (int i = 0; i < controls.Count; i++)
            {
                var ctl = controls[i];
                if (ctl is HtmlContainerControl)
                {
                    var div = (HtmlContainerControl)ctl;
                    if (div.TagName.ToLower() == "div" && div.Attributes["class"] != null && div.Attributes["class"].Contains("contentArea"))
                    {
                        if (firstContentArea == null)
                        {
                            firstContentArea = div;
                        }
                        if (defaultContentArea == null && div.Attributes["default"] != null && div.Attributes["default"].ToLower() == "true")
                        {
                            div.Attributes.Remove("default");
                            defaultContentArea = div;
                        }
                        var mdc = CMSPage.Current.ContentDefinition[div.ID].Modules;
                        if (mdc.Count == 0 && div.Attributes["inherit"] != null && div.Attributes["inherit"].ToLower() == "true")
                        {
                            div.Attributes.Remove("inherit");
                            var parentRecurse = CMSPage.Current.CMSPage.ParentPage;
                            int inheritanceAttempts = 0;
                            while (parentRecurse != null && mdc.Count == 0 && inheritanceAttempts < 10)
                            {
                                var parentVersion = parentRecurse.LiveVersion;
                                if (parentVersion == null)
                                {
                                    break;
                                }
                                mdc = parentVersion.ContentDefinition[div.ID].Modules;
                                mdc.ForEach(e => e.IsInherited = true);
                                totalNonInheritedModules -= mdc.Count;
                                parentRecurse = parentRecurse.ParentPage;
                                inheritanceAttempts++;
                            }
                        }
                        else if (div.Attributes["inherit"] != null)
                        {
                            div.Attributes.Remove("inherit");
                        }
                        mdc.ForEach(m => modulesToAdd.Add(new KeyValuePair<ModuleDefinition,Control>(m, div)));
                        totalNonInheritedModules += mdc.Count;
                        totalModules += mdc.Count;

                        // Clear out any containing code unless no controls, otherwise add a &nbsp;
                        if (mdc.Count == 0)
                            div.InnerHtml = "&nbsp;";
                        else
                            div.InnerHtml = "";
                    }
                }
                if (ctl.Controls != null)
                {
                    SetupContentAreas(ctl.Controls);
                }
            }
        }
    }
}

